from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect

from .models import Item, List
from .forms import ItemForm, ExistingListItemForm


# git log --oneline 查看提交日志，一行显示
# git reflog 查看历史提交记录
def home_page(request):
    return render(request, 'home.html', {'form': ItemForm()})


# 在列表List对象下添加列表项(Item对象)
# 使用Django表单
def view_list(request, pk):
    _list = List.objects.get(id=pk)
    form = ExistingListItemForm(for_list=_list)
    if request.method == 'POST':
        form = ExistingListItemForm(for_list=_list, data=request.POST)
        if form.is_valid():
            form.save(for_list=_list)
            # Item.objects.create(text=request.POST['text'], list=_list)
            return redirect(_list)
    return render(request, 'list.html', {'list': _list, 'form': form})


'''
def view_list(request, pk):
    _list = List.objects.get(id=pk)
    error = None
    if request.method == 'POST':
        try:
            item = Item.objects.create(text=request.POST['item_text'], list=_list)
            item.full_clean()  # 完整校验
            item.save()
            # return redirect(f'/lists/{_list.id}/')
            return redirect(_list)  # 背后使用List.get_absolute_url方法获得重定向URL
        except ValidationError as e:
            # print(e)  # {'text': ['This field cannot be blank.']}
            error = "You can't have an empty list item"
    return render(request, 'list.html', {'list': _list, 'error': error})
'''


# 添加列表项(Item对象),列表还没有，创建新的列表
# 只处理POST请求，如果表单认证不通过，返回home页面
def new_list(request):
    form = ItemForm(data=request.POST)
    if form.is_valid():
        _list = List.objects.create()
        form.save(for_list=_list)
        return redirect(_list)
    else:
        return render(request, 'home.html', {'form': form})
